<?php 
if (!defined('BASEPATH')) exit('No direct script access allowed'); 
/**
 * @todo  微信小程序调用类
 * @author Mk
 * @since  2017-12-27
 * @version 1.0v
 */
include_once 'wxBizDataCrypt.php';
class Weixin{
	private $appid;//小程序appid
	private $secret;//小程序secret
	/**
	 * 初始化方法
	 * @param String $appid
	 * @param String $secret
	 */
	function __construct($config){
		if(!$config['appid'] || !$config['secret']){
			log_message("error", "参数缺失,缺少微信appid或secret参数");
			return false;
		}
		$this->appid = $config['appid'];
		$this->secret = $config['secret'];
	}
	/**
	 * 微信用户登陆
	 * @param String $code
	 * @param String $encryptedData
	 * @param String $iv
	 */
	function wxLogin($code,$encryptedData,$iv){
		if(!$code || !$encryptedData || !iv){
			log_message("error","参数缺失:缺少code或encrypData或iv参数");
			return false;
		}
		$url="https://api.weixin.qq.com/sns/jscode2session?appid=".$this->appid."&secret=".$this->secret."&js_code=".$code."&grant_type=authorization_code";
		$apiData = $this->curl_Get($url);
		if(!isset($apiData["errcode"])){
			$sessionKey = json_decode($apiData)->session_key;
			$userInfo = new WXBizDataCrypt($this->appid,$this->secret);
			$errCode = $userInfo->decryptData($encryptedData, $iv, $data);
			if($errCode == 0){
				return $data;
			}else{
				log_message("error", "微信解析用户信息失败错误码:"+errCode);
				return false;
			}
		}
		log_message("error", "微信登陆失败错误码:"+$apiData["errcode"]);
		return false;
	}
	/**
	 * 获取微信openid
	 * @param String $code
	 */
	function getOpenid($code){
		if(!$code){
			log_message("error","参数缺失:缺少code参数");
			return false;
		}
		$url="https://api.weixin.qq.com/sns/jscode2session?appid=".$this->appid."&secret=".$this->secret."&js_code=".$code."&grant_type=authorization_code";
		$apiData = $this->curl_Get($url);
 		if(!isset($apiData["errcode"])){
 			return $apiData;
 		}
 		log_message("error", "微信登陆失败错误码:"+$apiData["errcode"]);
		return false;
	}
	private function curl_Get($url){
		return file_get_contents($url);
	}
}